import { addResizeListener, removeResizeListener } from '@/utils/resize-event.js'
// const echarts = require('echarts/dist/echarts.common.min')
class Chartutil {
  constructor () {
    this.option = {
      title: {
        show: true,
        left: '2%',
        text: '',
        textStyle: {
          color: '#37474f',
          fontStyle: 'normal',
          fontWeight: 'normal',
          fontFamily: '微软雅黑',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        x: 100,
        x2: 80,
        y2: 80
      },
      // xAxis: [],
      // yAxis: [],
      // legend: {},
      // toolbox: {
      //   show: false,
      //   feature: {
      //     mark: { show: true },
      //     dataView: { show: true, readOnly: false },
      //     magicType: {
      //       show: true,
      //       type: ['pie', 'funnel']
      //     }
      //   }
      // },
      calculable: false,
      series: []
    }
  }
  drawPie(params) {
    const commonColor = [
      '#61a4e4',
      "#00d897",
      "#fea858",
      "#ff8a8a",
      "#7f6aff",
      "#ffc533",
      "#ff589c",
      "#00cfda",
      "#4699ff",
      "#a7d778",
      "#9aa8d0",
    ]
    let options = JSON.parse(JSON.stringify(this.option))
    var scale = params.scale;
    let {
      _this,
      dom,
      unit, // 单位
      legend, // 图例
      series, // series
      color, // 颜色
      option // 配置
    } = params
    if (legend !== undefined) {
      if (Array.isArray(legend)) {
        Object.assign(options, {
          legend: {
            x: 'right',
            y: 40,
            orient: 'vertical',
            align: 'left',
            data: legend.map((item) => {
              return {
                name: item,
                icon: 'circle',
              }
            }),
            formatter: function (name) {
              var data = options.series[0].data;
              var total = 0;
              var tarValue;
              for (var i = 0, l = data.length; i < l; i++) {
                total += data[i].value;
                if (data[i].name == name) {
                  tarValue = data[i].value;
                }
              }
              var p = (tarValue / total * 100).toFixed(1);
              return name;
              // return name + ' ' + '(' + p + '%)';				

            }
          }
        }) && (series[0].label = { show: false }) && (series[0].labelLine = { show: false })
      } else {
        Object.assign(options, {
          legend: legend
        })
      }
    }
    Object.assign(options, {
      series: series,
      tooltip: {
        trigger: 'item'
      }
    })
    Object.assign(options, option)
    color ? options.color = color : options.color = commonColor
    this.drawAndResize(_this, dom, options)
  }
  drawBar(params) {
    let commonColor = [
      '#50a5f6',
      "#00d897",
      "#fea858",
      "#ff8a80",
      "#7f6aff",
      "#ffc533",
      "#ff5da3",
      "#00cfda",
      "#c1aea8",
      "#4699ff",
      "#ff8a8a",
      "#ff589c",
      "#a7d778",
      "#9aa8d0",
    ]
    /**
     * _this:  this对象，获取$echarts用
     * dom: 渲染的dom对象
     * series: series
     * legend: 图例, 对象或者数组
     * title: 标题
     * color: 颜色
     * xAxis: x轴
     * yAxis： y轴
     * gradient: 是否渐变
     * option: 配置项
     * grid: grid
     * unit: 单位
     * legend_top: legend top
     * barBorderRadius  bar图的borderRadius
     */
    let { legend_top = 0, _this, dom, istwo, series, legend, title, color, xAxis, yAxis, gradient, dataZoom, option, grid = { x: 40, y2: 40, x2: 40 }, unit = '', rotate = 0, barBorderRadius = 0, cb = null } = params
    let options = JSON.parse(JSON.stringify(this.option))

    // xAxis
    let xAxis_ = [
      {
        type: 'category',
        axisLine: {
          lineStyle: {
            color: '#777'
          }
        },
        axisLabel: {
          interval: 0,
          rotate: rotate
        },
        // data: xdata
        data: []
      }
    ]
    let yAxis_ = [
      {
        type: 'value',
        minInterval: 1,
        axisLine: { show: false },
        axisTick: { show: false },
        // axisLabel: {
        //   formatter: '{value} ' + unit
        // }
      }
    ]
    unit ? (yAxis_[0].name = '（' + (unit || '') + '）') : null
    if (dataZoom) {
      let dataZoomObj = {
        height: 10,
        backgroundColor: '#f1f3f7',
        fillerColor: '#00d897',
        showDataShadow: false,
        borderColor: 'transparent',
        filterMode: 'empty',
        showDetail: false,
        // handleStyle: {
        //   color: 'transparent'
        // }
        handleIcon: "M0,0 v9.7h5 v-9.7h-5 Z",
            handleStyle: { /*手柄的样式*/
                color: "#009d6d",
                borderColor: "#009d6d"
            },
      }
      if (Object.prototype.toString.call(dataZoom) === '[object Array]') {
        for (const vo in dataZoom) {
          if (vo.vertical === 'horizontal') {
            // 垂直方向
            dataZoomObj.width = 10
            delete dataZoomObj.height
          }
          Object.assign(vo, dataZoomObj)
        }
      } else {
        if (dataZoom.vertical === 'horizontal') {
          // 垂直方向
          dataZoomObj.width = 10
          delete dataZoomObj.height
        }
        Object.assign(dataZoom, dataZoomObj)
      }
      options.dataZoom = dataZoom
    }
    title !== undefined ? options.title.text = title : options.title.show = false
    /**
     * legend: []
     * 默认居于右上，水平放置
     */
    if (Array.isArray(legend)) {
      options.legend = {
        data: legend,
        right: 0,
        top: legend_top,
        type: 'scroll',
        orient: 'horizontal'
      }
    } else {
      if (legend) {
        options.legend = legend
      }
    }

    /**
     * 判断是x轴或者y轴
     */
    if (yAxis && !istwo) {
      xAxis_[0].data = yAxis
      options.xAxis = yAxis_
      options.yAxis = xAxis_
    } else {
      xAxis_[0].data = xAxis
      options.xAxis = xAxis_
      options.yAxis = yAxis_
    }
    if (yAxis && istwo) {
      options.yAxis = yAxis
    }
    if (grid) {
      options.grid = grid
    }
    if (gradient) {
      /**
       * 当gradient为true时，默认颜色满足我需要的,即[[],[],[]]
       */
      for (let i = 0, j = color.length; i < j; i++) {
        let arr = []
        if (color[i].length === 3) {
          arr = [
            { offset: 0, color: color[i][0] },
            { offset: 0.5, color: color[i][1] },
            { offset: 1, color: color[i][2] }
          ]
        } else {
          arr = [
            { offset: 0, color: color[i][0] },
            { offset: 1, color: color[i][1] }
          ]
        }
        if (series.length > 1) {
          // 判断渐变方向
          let ar = [0, 0, 0, 1]
          if (yAxis) {
            ar = [0, 0, 1, 0]
          }
          // 多条
          if (series[i].itemStyle) {
            series[i].itemStyle.color = new _this.$echarts.graphic.LinearGradient(
              ...ar,
              arr
            )
          } else {
            series[i].itemStyle = {
              color: new _this.$echarts.graphic.LinearGradient(
                ...ar,
                arr
              )
            }
          }
        } else {
          // 单条
          let num = series[0].data[i]
          series[0].data[i] = {
            name: xAxis[i],
            value: num,
            itemStyle: {
              color: new _this.$echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                arr
              )
            }
          }
        }
      }
    } else {
      if (color) {
        if (color.length >= series.length) {
          for (let i = 0, j = series.length; i < j; i++) {
            if (series[i].itemStyle) {
              series[i].itemStyle.color = color[i]
            } else {
              series[i].itemStyle = {
                color: color[i]
              }
            }
          }
        }
      } else {
        // if (color.length === series[0].data.length) {
        //   for (let i = 0, len = series[0].data.length; i < len; i++) {
        //     if (series[0].data[i].name) {
        //       if (series[0].data[i].itemStyle) {
        //         series[0].data[i].itemStyle['color'] = color[i]
        //       } else {
        //         series[0].data[i].itemStyle = {
        //           color: color[i]
        //         }
        //       }
        //     } else {
        //       series[0].data[i] = {
        //         name: yAxis ? yAxis[i] : xAxis[i],
        //         value: series[0].data[i],
        //         itemStyle: {
        //           color: color[i]
        //         }
        //       }
        //     }
        //   }
        // } else {
        options.color = commonColor
        // }
      }
    }
    for (let item of series) {
      if (item.itemStyle) {
        item.itemStyle.barBorderRadius = barBorderRadius
      } else {
        item.itemStyle = {
          barBorderRadius: barBorderRadius
        }
      }
    }
    options.series = series
    Object.assign(options, option)
    return this.drawAndResize(_this, dom, options, cb)
  }
  drawAndResize(_this, dom, options, cb) {
    try {
      const myChart = _this.$echarts.init(dom)
      cb || (cb = () => { })
      myChart.off('click')
      myChart.on('click', cb)
      myChart.clear()
      myChart.setOption(options)
      const fn = () => {
        myChart.resize()
      }
      removeResizeListener(dom, fn)
      /**
       * 改变事件
       */
      addResizeListener(dom, fn)
      return myChart
    } catch (error) {
      console.log(error)
    }
  }
}
// export const $echarts = echarts
export const ChartUtil = new Chartutil()
